package com.nttuan.mycalender;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.nttuan.adapter.ComingAdapter;
import com.nttuan.adapter.GridAdapter;
import com.nttuan.flows.ComingListener;
import com.nttuan.flows.PageChange;
import com.nttuan.model.dao.ContactDao;
import com.nttuan.model.dao.TaskDao;
import com.nttuan.model.dao.TrackDao;
import com.nttuan.model.dao.UserDao;
import com.nttuan.model.dao.service.ContactService;
import com.nttuan.model.dao.service.TaskService;
import com.nttuan.model.dao.service.TrackService;
import com.nttuan.model.dao.service.UserService;
import com.nttuan.model.entity.Contact;
import com.nttuan.model.entity.GridTask;
import com.nttuan.model.entity.Task;
import com.nttuan.model.entity.Track;
import com.nttuan.model.entity.User;
import com.nttuan.util.LogSupport;
import com.nttuan.util.Support;

import org.apache.commons.logging.Log;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;


public class FragmentCenter extends Fragment implements PageChange, ComingListener, AdapterView.OnItemClickListener {
    public static String TAG = "fragmentCenter";
    private final int DELAY = 5000;
    private Date currentDate = Calendar.getInstance().getTime();
    private String viewBy = PageChange.BY_DAY;
    private ListView listViewComing;
    private GridView gridViewComing;
    private ProgressBar progressBar;

    private ComingAdapter comingAdapter;
    private TaskService taskService;
    private List<Task> listComingTask;
    private List<GridTask> gridTaskList;

    private Timer countDownTimeLeft;
    private Context context;
    private UserService userService;
    private ContactService contactService;
    private TrackService trackService;
    private Handler handler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_center, container, false);
        init(rootView);

        return rootView;
    }

    private void init(View rootView) {
        //init view here
        listViewComing = (ListView) rootView.findViewById(R.id.listViewComing);
        gridViewComing = (GridView) rootView.findViewById(R.id.gridByWeek);
        progressBar = (ProgressBar) rootView.findViewById(R.id.progressBarCenter);
        //init available
        taskService = TaskDao.getInstance(context);
        userService = UserDao.getInstance(context);
        contactService = ContactDao.getInstance(context);
        trackService = TrackDao.getInstance(context);
        listComingTask = new ArrayList<Task>();
        countDownTimeLeft = new Timer();
        comingAdapter = new ComingAdapter(context, listComingTask, viewBy);

        listViewComing.setAdapter(comingAdapter);

        //init action
        initListener();
        //load
        new loadComing(Calendar.getInstance().getTime()).execute();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        Bundle bundle = new Bundle();
        int userId = userService.getMe().getUserId();
        int taskId = listComingTask.get(i).getTaskId();
        if (contactService.checkLeader(taskId, userId))
            bundle.putInt(AddNewActivity.KEY_ACTION, AddNewActivity.KEY_ACTION_VIEW);
        else
            bundle.putInt(AddNewActivity.KEY_ACTION, AddNewActivity.KEY_ACTION_VIEW_INVITE);
        bundle.putInt(AddNewActivity.KEY_TASK_ID, taskId);
        Intent intent = new Intent(context, AddNewActivity.class);
        intent.putExtra(AddNewActivity.KEY_BUNDLE, bundle);
        startActivity(intent);

    }

    private void initListener() {
        comingAdapter.setListener(this);
        listViewComing.setOnItemClickListener(this);
    }

    private class loadComing extends AsyncTask<String, Void, Void> {
        //   private ProgressDialog dialog;
        private Date date;

        public loadComing(Date date) {
            if (date == null)
                date = Calendar.getInstance().getTime();
            this.date = date;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }

        @Override
        protected Void doInBackground(String... sDate) {
            switch (viewBy) {
                case PageChange.BY_DAY:
                    listComingTask = taskService.comingTasks(date, true);
                    break;
                case PageChange.BY_WEEK:
                    listComingTask = taskService.taskOfWeek(date, true);
                    break;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressBar.setVisibility(View.GONE);
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            if (viewBy.equals(PageChange.BY_DAY)) {
                comingAdapter = new ComingAdapter(context, listComingTask, viewBy);
                listViewComing.setAdapter(comingAdapter);
                initListener();
                startUpdate();
            } else {
                stopUpdate();
                comingAdapter = new ComingAdapter(context, listComingTask, viewBy);
                listViewComing.setAdapter(comingAdapter);
                initListener();
            }
        }
    }

    class loadTaskByWeek extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            gridTaskList = new ArrayList<GridTask>();
            gridTaskList.add(new GridTask(Calendar.getInstance().getTime(), 3));
            gridTaskList.add(new GridTask(Calendar.getInstance().getTime(), 4));
            gridTaskList.add(new GridTask(Calendar.getInstance().getTime(), 5));
            gridTaskList.add(new GridTask(Calendar.getInstance().getTime(), 6));
            gridTaskList.add(new GridTask(Calendar.getInstance().getTime(), 8));
            gridTaskList.add(new GridTask(Calendar.getInstance().getTime(), 9));
            gridTaskList.add(new GridTask(Calendar.getInstance().getTime(), 10));
            GridAdapter gridAdapter = new GridAdapter(getActivity(), gridTaskList);
            gridViewComing.setAdapter(gridAdapter);
            gridViewComing.setOnItemClickListener(FragmentCenter.this);
            return null;
        }

        @Override
        protected void onPreExecute() {
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            progressBar.setVisibility(View.GONE);
            gridViewComing.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    new loadComing(gridTaskList.get(i).getDate()).execute();
                    gridViewComing.setVisibility(View.GONE);
                    listViewComing.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    private Runnable updateTask = new Runnable() {
        @Override
        public void run() {

            comingAdapter.notifyDataSetInvalidated();
            handler.postDelayed(this, DELAY);
        }
    };

    private void stopUpdate() {
        if (handler != null)
            handler.removeCallbacks(updateTask);
    }

    private void startUpdate() {
        if (handler != null)
            handler.postAtTime(updateTask, DELAY);
    }

    private boolean isLeader(int taskId, int userId) {
        User u = userService.user(userId);
        List<Contact> contacts = contactService.contactsByTask(taskId);
        for (Contact contact : contacts) {
            if (contact.isLeader() && contact.getUser().getUserId() == u.getUserId())
                return true;
        }
        return false;
    }

    private void deleteTask(final int taskId) {
        final Dialog dialog = new Dialog(context);

        View view = LayoutInflater.from(context).inflate(R.layout.dialog_confirm, null);
        dialog.setContentView(view);
        Button btnOk = (Button) view.findViewById(R.id.btnOkConfirmDialog);
        Button btnCancel = (Button) view.findViewById(R.id.btnCancelConfirmDialog);
        final EditText txtMessage = (EditText) view.findViewById(R.id.txtMessageDialog);
        final Task task = taskService.task(taskId);
        if (task.getPublicId() == 0 || (!isLeader(taskId, userService.getMe().getUserId()) && task.getPublicId() != 0))
            txtMessage.setVisibility(View.GONE);
        else
            txtMessage.setVisibility(View.VISIBLE);

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (txtMessage.getVisibility() == View.GONE) {
                    if (taskService.active(taskId, false))
                        new loadComing(currentDate).execute();
                    else
                        Toast.makeText(getActivity(), R.string.delete_error, Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    return;
                }
                if (txtMessage.getText().equals("") || txtMessage.getText().toString().length() < 10) {
                    Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.vibrate);
                    txtMessage.startAnimation(animation);
                    return;
                }
                if (taskService.active(taskId, false)) {
                    Track track = new Track();
                    track.setActon(Track.ACTION_DELETE_INVITE);
                    track.setMessage(txtMessage.getText().toString());
                    track.setCommit(false);
                    track.setActive(true);
                    track.setTask(new Task(taskId));
                    track.setLastTime(Support.toDateTime("1111-11-11 11:11:00", false));
                    if (trackService.create(track)) {
                        new loadComing(currentDate).execute();
                        LogSupport.saveLog(getActivity(), taskService.getAlarm(Calendar.getInstance().getTime()));
                    }
                    else
                        Toast.makeText(getActivity(), R.string.delete_error, Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(context, R.string.delete_error, Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    @Override
    public void selectedPage(int page, Date date) {
        if (page == 0) {
            currentDate = date;
            new loadComing(date).execute();
        }
    }

    @Override
    public void changeDate(Date date) {
        currentDate = date;
        new loadComing(date).execute();
    }

    @Override
    public void viewBy(String by) {
        this.viewBy = by;
        if (viewBy.equals(PageChange.BY_DAY)) {
            gridViewComing.setVisibility(View.GONE);
            listViewComing.setVisibility(View.VISIBLE);
            new loadComing(currentDate).execute();
        } else {
            listViewComing.setVisibility(View.GONE);
            gridViewComing.setVisibility(View.VISIBLE);
            new loadTaskByWeek().execute();
        }

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = getActivity();
        ((MainActivity) context).pageChangeCenter = this;
    }

    @Override
    public void viewDetails(int taskId) {

    }

    @Override
    public void edit(int taskId) {
        Bundle bundle = new Bundle();
        bundle.putInt(AddNewActivity.KEY_ACTION, AddNewActivity.KEY_ACTION_VIEW);
        bundle.putInt(AddNewActivity.KEY_TASK_ID, taskId);
        Intent intent = new Intent(context, AddNewActivity.class);
        intent.putExtra(AddNewActivity.KEY_BUNDLE, bundle);
        startActivity(intent);
    }

    @Override
    public void delete(int taskId) {
        deleteTask(taskId);
    }

    @Override
    public void changeRemain(int taskId) {
//        Dialog dialog = new Dialog(context);
//        View view = LayoutInflater.from(context).inflate(R.layout.dialog_change_remain, null);
//        dialog.setContentView(view);
//        Switch btnSwitch = (Switch)view.findViewById(R.id.switchRemainDialog);
//    //    SlideEditText txt = (SlideEditText)view.findViewById(R.id.slideRemainDialog);
//   //     SelectView select =(SelectView)view.findViewById(R.id.selectRemainDialog);
//    //    select.setData(getResources().getStringArray(R.array.duringType));
//
//        dialog.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countDownTimeLeft != null)
            countDownTimeLeft.cancel();
    }

    @Override
    public void onResume() {
        super.onResume();
        new loadComing(currentDate).execute();
    }
}
